<template>
  <div class="app-container">
    <div style="font-size: 25px;">账款</div>
    <el-divider></el-divider>
    <el-row>
    <el-form ref="form" :model="form"  label-width="80px">
      <el-col :span="6">
        <el-form-item label="采购单号" prop="poNo" style="width: 300px">
          <span style="display:inline-block;width:200px;font-weight:bold;">
            {{form.poNo}}
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="应付金额" style="width: 300px" >
          <span  style="display:inline-block;width:200px;font-weight:bold;">
            {{form.amountPayable}}
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="已付金额" style="width: 300px" >
          <span  style="display:inline-block;width:200px;font-weight:bold;">
            {{form.amountPaid}}
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="未付金额" style="width: 300px" >
          <span  style="display:inline-block;width:200px;font-weight:bold;">
            {{form.unpaidAmount}}
          </span>
        </el-form-item>
      </el-col>
    </el-form>
    </el-row>
    <el-divider></el-divider>
    <div style="width: 400px" class="t">
    <el-form :model="submitFrom" :rules="rules" label-width="90px">
        <el-form-item label="付款金额" prop="amountPayment" style="width: 400px">
          <el-input
            v-model="submitFrom.amountPayment"
            maxlength="20"
            @keyup.native="submitFrom.amountPayment = submitFrom.amountPayment = submitFrom.amountPayment.replace(/[^\d.]/g,'');
                           submitFrom.amountPayment = submitFrom.amountPayment.replace(/\.{2,}/g,'.');
                           submitFrom.amountPayment = submitFrom.amountPayment.replace(/^\./g,'');
                           submitFrom.amountPayment = submitFrom.amountPayment.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                           submitFrom.amountPayment = submitFrom.amountPayment.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
            placeholder="请输入付款金额"
            clearable
          />
        </el-form-item>
        <el-form-item label="付款日期" prop="paymentTime" style="width: 400px" >
          <el-date-picker clearable
                          style="width:310px"
                          v-model="submitFrom.paymentTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择付款日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="付款人" prop="drawee" style="width: 400px" >
          <el-input
            v-model="submitFrom.drawee"
            maxlength="20"
            placeholder="请输入付款人"
            clearable
          />
        </el-form-item>


          <el-form-item label="付款凭证"  prop="paymentVoucher" style="width: 400px" >
            <div class="upload">
              <div class="upload_warp">
                <div class="upload_warp_left" @click="thumbnailFileClick">
                  <img src="../../voucher.png">
                </div>
                <div class="upload_warp_right" @drop="drop($event)" @dragenter="dragenter($event)"
                     @dragover="dragover($event)">
                  或者将文件拖到此处
                </div>
              </div>
              <input @change="thumbnailFileChange($event)" type="file" id="upload_goods_thum" multiple
                     style="display: none"/>
                            <div v-show="fileList.length!=0">
                              <a :href=voucherUrl target="_blank">查看文件</a>
                            </div>
            </div>
          </el-form-item>


        <el-form-item label="付款账户" prop="paymentAccount" style="width: 400px" >
          <el-select
            v-model="submitFrom.paymentAccount"
            placeholder="付款账户"
            clearable
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="dict in accountList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="付款备注" style="width: 400px" >
          <el-input
            v-model="submitFrom.paymentRemarks"
            placeholder="请输入付款备注"
            type="textarea"
            maxlength="250"
            clearable
          />
        </el-form-item>
    </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button type="primary" @click="disburse">保存付款信息</el-button>
        <el-button type="primary" @click="cancel">返 回</el-button>
      </div>
    </div>


  </div>

</template>

<script>

import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getCollection, updateCollection, uploadFile} from "@/api/erp/collection";
import {get_minio_bucketName, get_minio_url, minioClient, random_string} from "../../../../minio";
import {listAccount} from "@/api/erp/account";
import {getCopeWith, getCopeWithLeftPaymentRecord, updateCopeWith} from "@/api/erp/copeWith";

let stream = require('stream')

export default {
  name: "copeWith",
  dicts: ['erp_payment_type'],
  data() {
    return {
      //凭证文件地址
      voucherUrl:null,
      //文件list
      fileList: [],
      //资金账户list
      accountList: [],
      //提交参数
      submitFrom: {},
      //表单参数
      form: {},
      // 表单校验
      rules: {
        amountPayment: [
          { required: true, message: "请输入付款金额", trigger: "blur" }
        ],
        paymentTime: [
          { required: true, message: "请选择付款日期", trigger: "blur" }
        ],
        drawee: [
          { required: true, message: "请输入付款人", trigger: "blur" }
        ],
        paymentVoucher: [
          { required: true, message: "", trigger: "blur" }
        ],
        paymentAccount: [
          { required: true, message: "请选择付款账户", trigger: "blur" }
        ],
      },
      // 遮罩层
      loading: true,
    };
  },
  created() {

    this.getList();
    this.getAccount();
  },

  methods: {

    //刷新页面数据
    getList() {
      const id = this.$route.query.id
      getCopeWithLeftPaymentRecord(id).then(response => {
        this.form = response.data;
        if(this.form.amountPaid === null || this.form.amountPaid === ""|| this.form.amountPaid === undefined){
          this.form.amountPaid = 0;
        }
        if(this.form.unpaidAmount === null || this.form.unpaidAmount === ""|| this.form.unpaidAmount === undefined){
          this.form.unpaidAmount = 0;
        }
      });
    },

    //保存付款信息
    disburse() {
      if(this.submitFrom.amountPayment === null ||this.submitFrom.amountPayment === "" ||this.submitFrom.amountPayment ===undefined){
        this.$modal.msgError("请填写付款金额");
        return;
      }
      if(this.submitFrom.paymentTime === null ||this.submitFrom.paymentTime === "" ||this.submitFrom.paymentTime ===undefined){
        this.$modal.msgError("请选择付款日期");
        return;
      }
      if(this.submitFrom.drawee === null ||this.submitFrom.drawee === "" ||this.submitFrom.drawee ===undefined){
        this.$modal.msgError("请填写付款人");
        return;
      }
      if(this.voucherUrl === null ||this.voucherUrl === "" ||this.voucherUrl ===undefined){
        this.$modal.msgError("请上传付款凭证");
        return;
      }
      if(this.submitFrom.paymentAccount === null ||this.submitFrom.paymentAccount === "" ||this.submitFrom.paymentAccount ===undefined){
        this.$modal.msgError("请选择付款账户");
        return;
      }
      /*定义一个付款参数*/
      let num = 0;
      num = Number(this.submitFrom.amountPayment) + Number(this.form.amountPaid);
      if(num > this.form.amountPayable){
        this.$modal.alertError("付款总额大于应付金额，请修改！"+"当前应付总额为："+this.form.amountPayable+"，"+"付款总额为："+num);
        return;
      }
      this.submitFrom.id = this.$route.query.id
      this.submitFrom.purchaseId = this.$route.query.purchaseId
      this.submitFrom.paymentVoucher = this.voucherUrl
      updateCopeWith(this.submitFrom).then(res =>{
        if (res.code == 200){
          this.$modal.msgSuccess("付款成功")
          this.cancel();
        }
      })
    },
// 取消按钮
    cancel() {
      this.$router.push({path: '/finace/copeWith'});
    },
    //获取资金账户list
    getAccount() {
      listAccount().then(response => {
        this.accountList = response.rows;
      });
    },
    //上传文件
    thumbnailFileClick() {
      document.getElementById('upload_goods_thum').click()
    },
    //拖拽文件触发
    drop(el) {
      el.stopPropagation();
      el.preventDefault();
    },
    //拖拽效果
    dragenter(el) {
      el.stopPropagation();
      el.preventDefault();
    },
    //上传文件方法
    thumbnailFileChange(el) {
      this.uploadVoucher(el.target.files[0])
    },
    //上传minio
    uploadVoucher(fileObj, index) {
      let vm = this
      if (fileObj) {
        let file = fileObj
        let that = this
        //判断是否选择了文件
        if (file == undefined) {
          //未选择
          console.log("请上传文件")
        } else {
          //选择
          //获取文件类型及大小
          const fileName = "collection/voucher/" + random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop();
          const mineType = file.type
          const fileSize = file.size
          //参数
          let metadata = {
            "content-type": mineType,
            "content-length": fileSize
          }
          //判断储存桶是否存在
          minioClient.bucketExists(get_minio_bucketName(), function (err) {
            if (err) {
              if (err.code == 'NoSuchBucket') return console.log("bucket does not exist.")
              return console.log(err)
            }
            //存在
            console.log('Bucket exists.')
            //准备上传
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function (e) {
              const dataurl = e.target.result
              //base64转blob
              const blob = vm.toBlob(dataurl)
              //blob转arrayBuffer
              let reader2 = new FileReader()
              reader2.readAsArrayBuffer(blob)
              reader2.onload = function (ex) {
                //定义流
                let bufferStream = new stream.PassThrough();
                //将buffer写入
                bufferStream.end(new Buffer(ex.target.result));
                //上传
                minioClient.putObject(get_minio_bucketName(), fileName, bufferStream, fileSize, metadata, function (err, etag) {
                  if (err == null) {
                    minioClient.presignedGetObject(get_minio_bucketName(), fileName, 24 * 60 * 60, function (err, presignedUrl) {
                      if (err) return console.log(err)
                      that.form.collectionVoucher = get_minio_url() + fileName;
                      that.fileList.push(get_minio_url() + fileName);
                      that.voucherUrl = get_minio_url() + fileName;
                    })
                  }
                })
              }
            }
          })
        }
      }
    },
    //base64转blob
    toBlob(base64Data) {
      let byteString = base64Data
      if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(base64Data.split(',')[1]) // base64 解码
      } else {
        byteString = unescape(base64Data.split(',')[1])
      }
      // 获取文件类型
      let mimeString = base64Data.split(';')[0].split(":")[1] // mime类型
      let uintArr = new Uint8Array(byteString.length) // 创建视图
      for (let i = 0; i < byteString.length; i++) {
        uintArr[i] = byteString.charCodeAt(i)
      }
      // 生成blob
      const blob = new Blob([uintArr], {
        type: mimeString
      })
      return blob
    },
  }

}

</script>
<style>
.t{
  margin: auto;
}

.upload_warp_img_div img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
}


.upload_warp_right {
  float: left;
  width: 50%;
  margin-left: 2%;
  height: 100%;
  border: 1px dashed #999;
  border-radius: 4px;
  line-height: 130px;
  color: #999;
}

.upload_warp_left img {
  margin-top: 32px;
}

.upload_warp_left {
  float: left;
  width: 45%;
  height: 100%;
  border: 1px dashed #999;
  border-radius: 4px;
  cursor: pointer;
}

.upload_warp {
  margin: 14px;
  height: 130px;
}

.upload {
  border: 1px solid #ccc;
  background-color: #fff;
  width: 100%;
  box-shadow: 0px 1px 0px #ccc;
  border-radius: 4px;
  text-align: center;
}

</style>
